<?php
/*
 * Copyright (c) 2022.  Liuhongbin All rights reserved.
 * @domain http://dkyx.cc
 * @author liuhongbin <514660094@qq.com>
 */

namespace app\controller\douyin;


use app\common\controller\DouyinController;
use app\common\model\douyin\DouyinUser;
use hiduoke\services\douyin\DouyinService;
use Overtrue\Socialite\Exceptions\AuthorizeFailedException;
use think\Exception;
use think\facade\Cache;

class Oauth extends DouyinController
{
    public function index()
    {
        return $this->success('抖音网页授权相关回调接口');
    }

    public function callBack()
    {
        $dy = new DouyinService();
        $DouyinUser = new DouyinUser();
        $plaid = get_plaid();
        $code = input('code', '');
        if (!$plaid) {
            die('plaid不存在');
        }
        try {
            $user = $dy->getProvider()->userFromCode($code);
            $raw = $user->getRaw();
            if ($raw['error_code'] != 0) {
                throw new \think\Exception($raw['description'], -1);
            }
            $douyin_user = $DouyinUser->where(['open_id' => $raw['open_id'], 'plaid' => $plaid])->findOrEmpty();
            $user_data = array(
                'nickname'      => $raw['nickname'],
                'avatar'        => $raw['avatar'],
                'gender'        => $raw['gender'],
                'city'          => $raw['city'],
                'country'       => $raw['country'],
                'access_token'  => $user->getAccessToken(),
                'refresh_token' => $user->getRefreshToken(),
                'last_addon'    => get_addon()
            );
            if (isset($douyin_user['first_addon']) && $douyin_user['first_addon'] == '') {
                $user_data['first_addon'] = get_addon();
            }
            if ($douyin_user->isEmpty()) {
                //写入用户信息
                $user_insert_data = array(
                    'open_id' => $raw['open_id'],
                    'remark'  => '',
                    'plaid'   => $plaid,
                );
                $user_insert_data = array_merge($user_data, $user_insert_data);
                $douyin_user->save($user_insert_data);
            } else {
                //更新用户信息
                $douyin_user->save($user_data);
            }
            session('open_id', $douyin_user->open_id);
            Cache::set($this->getKey('dy_user'), $douyin_user->toArray());
//            $target_url = Cache::get($this->getKey('target_url'));
            $target_url = input('back', $this->getKey('target_url'));
            if ($target_url) {
                Cache::delete($this->getKey('target_url'));
            }
            if (strpos($target_url, '&ref=douyin')) {
                $target_url = str_replace('&ref=douyin', '', $target_url) . '&ref=douyin#douyin_redirect';
            } else {
                $target_url .= '&ref=douyin#douyin_redirect';
            }
            to($target_url);
        } catch (AuthorizeFailedException $e) {
            showMessage($e->body['data']['description'] ?? $e->getMessage());
        }
    }

    protected function getKey($string)
    {
        return $string . input('sid') . '_' . get_plaid();
    }
}
